<template>
  <div class="user-manage-container">
    <el-card class="manage-card">
      <template #header>
        <!-- <span>用户综合管理</span> -->
      </template>

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.search"
              placeholder="请输入用户ID"
              clearable
              @clear="handleReset"
            />
          </el-form-item>

          <el-form-item label="状态">
            <el-select v-model="searchForm.state" placeholder="请选择" style="width: 80px;">
              <el-option label="全部" value="" />
              <el-option label="正常" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 用户列表区域 -->
      <div class="user-list-section">
        <!-- <h3>用户列表 (总数: {{ total }})</h3> -->

        <!-- 表格 -->
        <el-table
          :data="userList"
          border
          style="width: 100%"
          v-loading="tableLoading"
          :row-style="{ height: '60px' }"
        >
          <!-- 原有列 -->
          <el-table-column prop="buyerUserId" label="用户ID" width="120" />
          <el-table-column prop="name" label="昵称" width="150" />
          <el-table-column prop="phone" label="手机号" width="150" />
  

          <!-- 新增字段列 -->
          <el-table-column prop="balance" label="可用余额" width="120">
            <template #default="{ row }">
              {{ Number(row.balance || 0).toFixed(2) }}
            </template>
          </el-table-column>

          <el-table-column prop="frozenBalance" label="冻结余额" width="120">
            <template #default="{ row }">
              {{ Number(row.frozenBalance || 0).toFixed(2) }}
            </template>
          </el-table-column>

          <el-table-column prop="payPasswordLockTime" label="支付密码锁定时间" width="150">
            <template #default="{ row }">
              {{ row.payPasswordLockTime || '-' }}
            </template>
          </el-table-column>

          <el-table-column prop="disableTime" label="封禁时长" width="180">
            <template #default="{ row }">
              {{ !row.disableTime || (typeof row.disableTime === 'object' && Object.keys(row.disableTime).length === 0) ? '-' : row.disableTime.replace('T', ' ') }}
            </template>
          </el-table-column>

          <el-table-column label="冻结状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.frozenBalance > 0 ? 'danger' : 'success'">
                {{ row.frozenBalance > 0 ? '已冻结' : '正常' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="用户状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.state === 1 ? 'success' : 'danger'">
                {{ row.state === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- IM状态列 -->
          <el-table-column label="IM状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.ifAllowIm === 1 ? 'success' : 'danger'">
                {{ row.ifAllowIm === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 动态发布状态列 -->
          <el-table-column label="动态发布状态" width="130">
            <template #default="{ row }">
              <el-tag :type="row.ifAllowTrends === 1 ? 'success' : 'danger'">
                {{ row.ifAllowTrends === 1 ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>

          <!-- 操作列 -->
          <el-table-column label="操作" width="350">
            <template #default="{ row }">
                <div class="operation-buttons">
                  <!-- 禁用/启用按钮 -->
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleBan(row)"
                    v-if="row.state === 1"
                  >
                    禁用
                  </el-button>
                  <el-button
                    size="small"
                    type="warning"
                    @click="handleUnban(row)"
                    v-if="row.state === 0"
                  >
                    启用
                  </el-button>

                  <!-- 冻结/解冻钱包按钮 -->
                  <el-button
                    size="small"
                    type="primary"
                    @click="handleFreeze(row)"
                    v-if="row.frozenBalance <= 0"
                  >
                    冻结钱包
                  </el-button>
                  <el-button
                    size="small"
                    type="info"
                    @click="handleUnfreeze(row)"
                    v-if="row.frozenBalance > 0"
                  >
                    解冻钱包
                  </el-button>
                  
                  <!-- 禁用/启用用户发布动态按钮 -->
                  <el-button
                    size="small"
                    type="warning"
                    @click="handleTrendsDisable(row)"
                    v-if="row.ifAllowTrends === 1"
                  >
                    禁用发布动态
                  </el-button>
                  <el-button
                    size="small"
                    type="success"
                    @click="handleTrendsEnable(row)"
                    v-if="row.ifAllowTrends === 0"
                  >
                    启用发布动态
                  </el-button>
                  
                  <!-- 禁用/启用用户IM按钮 -->
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleImDisable(row)"
                    v-if="row.ifAllowIm === 1"
                  >
                    禁用IM
                  </el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="handleImEnable(row)"
                    v-if="row.ifAllowIm === 0"
                  >
                    启用IM
                  </el-button>
                </div>
              </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-scroll-wrapper">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            class="pagination-wrapper"
          ></el-pagination>
        </div>
      </div>

      <!-- 对话框：确认禁用 -->
      <el-dialog v-model="banDialogVisible" :title="`确认${banAction}`" width="400px">
        <template v-if="banAction === '禁用'">
          <p>确定要禁用用户 <strong>{{ banUser?.name }}</strong> 的账号吗？</p>
          <el-form :model="{ banTimeOption, banReason }" label-width="100px" style="margin-top: 20px;">
            <el-form-item label="禁用时长">
              <el-radio-group v-model="banTimeOption" size="small" style="width: 100%;">
                <el-radio-button label="1m">1分钟</el-radio-button>
                <el-radio-button label="1h">1小时</el-radio-button>
                <el-radio-button label="1w">1周</el-radio-button>
                <el-radio-button label="1M">1月</el-radio-button>
                <el-radio-button label="1y">1年</el-radio-button>
                <el-radio-button label="permanent">永久</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="禁用原因">
              <el-input
                v-model="banReason"
                placeholder="请输入禁用原因"
                type="textarea"
                :rows="2"
              />
            </el-form-item>
          </el-form>
        </template>
        <template v-else>
          <p>确定要启用用户 <strong>{{ banUser?.name }}</strong> 的账号吗？</p>
        </template>
        <template #footer>
          <el-button @click="banDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmBan">确定</el-button>
        </template>
      </el-dialog>
      
      <!-- 对话框：确认禁用/启用发布动态 -->
      <el-dialog v-model="trendsDialogVisible" :title="`确认${trendsAction}`" width="400px">
        <p>确定要${trendsAction}用户 <strong>{{ trendsUser?.name }}</strong> 的发布动态权限吗？</p>
        <template #footer>
          <el-button @click="trendsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmTrendsAction">确定</el-button>
        </template>
      </el-dialog>
      
      <!-- 对话框：确认禁用/启用IM -->
      <el-dialog v-model="imDialogVisible" :title="`确认${imAction}`" width="400px">
        <p>确定要${imAction}用户 <strong>{{ imUser?.name }}</strong> 的IM功能吗？</p>
        <template #footer>
          <el-button @click="imDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmImAction">确定</el-button>
        </template>
      </el-dialog>

      <!-- 对话框：冻结钱包 -->
      <el-dialog v-model="freezeDialogVisible" title="冻结钱包" width="500px">
        <el-form :model="freezeForm" label-width="100px">
          <el-form-item label="冻结金额">
            <el-input-number
              v-model="freezeForm.amount"
              :min="0"
              :max="999999"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="冻结时长">
            <el-select v-model="freezeForm.expireTimeOption" placeholder="请选择">
              <el-option label="1小时" value="1h" />
              <el-option label="1天" value="1d" />
              <el-option label="1周" value="1w" />
              <el-option label="1个月" value="1m" />
              <el-option label="1年" value="1y" />
            </el-select>
          </el-form-item>
          <el-form-item label="原因">
            <el-input
              v-model="freezeForm.reason"
              placeholder="请输入冻结原因"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="freezeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmFreeze">提交</el-button>
        </template>
      </el-dialog>

      <!-- 对话框：解冻钱包 -->
      <el-dialog v-model="unfreezeDialogVisible" title="解冻钱包" width="400px">
        <p>确定要解冻用户 <strong>{{ unfreezeUser.name }}</strong> 的钱包吗？</p>
        <template #footer>
          <el-button @click="unfreezeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmUnfreeze">确定</el-button>
        </template>
      </el-dialog>


    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserService, UserItem, UpdateUserStatusParams, WalletFreezeParams, BuyerTrendsParam, BuyerImParam } from '@/api/userApi'

// 数据相关
const tableLoading = ref(false)
const userList = ref<UserItem[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = reactive({
  search: '',
  state: ''
})

// 禁用/启用相关
const banDialogVisible = ref(false)
const banUser = ref<UserItem | null>(null)
const banAction = ref('')
// 禁用时间选择相关
const banTimeOption = ref('permanent') // 默认永久禁用
const banReason = ref('')

// 冻结钱包相关
const freezeDialogVisible = ref(false)
const freezeForm = reactive({
  amount: 0,
  expireTimeOption: '1d',
  reason: ''
})
const freezeTargetUser = ref<UserItem | null>(null)

// 解冻钱包相关
const unfreezeDialogVisible = ref(false)
const unfreezeUser = ref<UserItem | null>(null)

// 用户动态状态相关
const trendsDialogVisible = ref(false)
const trendsUser = ref<UserItem | null>(null)
const trendsAction = ref('')

// 用户IM状态相关
const imDialogVisible = ref(false)
const imUser = ref<UserItem | null>(null)
const imAction = ref('')



// 加载用户列表
const loadUserList = async () => {
  tableLoading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      search: searchForm.search,
      state: searchForm.state
    }
    
    const response = await UserService.getUserBanList(params)
    console.log('API Response:', response) // 调试信息
    
    if (response.code === "200") {
      userList.value = response.data.list || []
      total.value = response.data.total || 0
      console.log('User List:', userList.value) // 调试信息
    } else {
      ElMessage.error(response.message || '加载失败')
    }
  } catch (error: any) {
    ElMessage.error('请求失败：' + error.message)
  } finally {
    tableLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  loadUserList()
}

// 重置
const handleReset = () => {
  searchForm.search = ''
  searchForm.state = ''
  currentPage.value = 1
  loadUserList()
}

// 分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  loadUserList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  loadUserList()
}

// 禁用用户
const handleBan = (user: UserItem) => {
  banUser.value = user
  banAction.value = '禁用'
  banTimeOption.value = 'permanent' // 重置为默认值
  banReason.value = '' // 清空原因
  banDialogVisible.value = true
}

// 启用用户
const handleUnban = (user: UserItem) => {
  banUser.value = user
  banAction.value = '启用'
  banDialogVisible.value = true
}

// 提交禁用/启用
const confirmBan = async () => {
  if (!banUser.value) return
  
  try {
    if (banAction.value === '禁用') {
      // 计算禁言时长
      const banTime = calculateBanTime(banTimeOption.value)
      
      // 构建禁用参数，包含banTime字段
      const params: UpdateUserStatusParams & { banTime?: string; reason?: string } = {
        buyerUserId: banUser.value.buyerUserId,
        state: 0, // 0-禁用
        banTime,
        reason: banReason.value
      }
      
      const response = await UserService.updateUserStatus(params)
      
      if (response.code === "200") {
        ElMessage.success('禁用成功')
        banDialogVisible.value = false
        loadUserList()
      } else {
        ElMessage.error(response.message || '禁用失败')
      }
    } else {
      // 启用用户：使用原有的启用接口
      const params: UpdateUserStatusParams = {
        buyerUserId: banUser.value.buyerUserId,
        state: 1 // 1-启用
      }
      
      const response = await UserService.updateUserStatus(params)
      
      if (response.code === "200") {
        ElMessage.success('启用成功')
        banDialogVisible.value = false
        loadUserList()
      } else {
        ElMessage.error(response.message || '启用失败')
      }
    }
  } catch (error: any) {
    ElMessage.error('提交失败：' + error.message)
  }
}

// 解冻钱包
const handleUnfreeze = (user: UserItem) => {
  unfreezeUser.value = user
  unfreezeDialogVisible.value = true
}

// 提交解冻
const confirmUnfreeze = async () => {
  if (!unfreezeUser.value) return

  const params: WalletFreezeParams = {
    buyerUserId: unfreezeUser.value.buyerUserId,
    actionType: 1, // 1-解冻
    amount: 0,
    expireTime: '',
    reason: ''
  }

  try {
    const response = await UserService.freezeWallet(params)
    
    if (response.code === "200") {
      ElMessage.success('解冻成功')
      unfreezeDialogVisible.value = false
      loadUserList()
    } else {
      ElMessage.error(response.message || '解冻失败')
    }
  } catch (error: any) {
    ElMessage.error('网络错误：' + error.message)
  }
}

// 冻结钱包
const handleFreeze = (user: UserItem) => {
  freezeTargetUser.value = user
  freezeForm.amount = 0
  freezeForm.reason = ''
  freezeDialogVisible.value = true
}

// 计算截止时间戳 - 为冻结功能保留
const calculateExpireTime = (option: string) => {
  const now = new Date()
  switch (option) {
    case '1m': return now.getTime() + 60 * 1000 // 1分钟
    case '1h': return now.getTime() + 60 * 60 * 1000 // 1小时
    case '1w': return now.getTime() + 7 * 24 * 60 * 60 * 1000 // 1周
    case '1M': return now.getTime() + 30 * 24 * 60 * 60 * 1000 // 1月
    case '1y': return now.getTime() + 365 * 24 * 60 * 60 * 1000 // 1年
    case '1d': return now.getTime() + 24 * 60 * 60 * 1000 // 1天
    case 'permanent': return null // 永久禁用
    default: return null
  }
}

// 计算禁言时长 - 返回标准ISO 8601格式字符串（yyyy-MM-dd'T'HH:mm:ss）
const calculateBanTime = (option: string): string | null => {
  const now = new Date()
  let targetDate: Date
  
  switch (option) {
    case '1m': targetDate = new Date(now.getTime() + 60 * 1000); break // 1分钟
    case '1h': targetDate = new Date(now.getTime() + 60 * 60 * 1000); break // 1小时
    case '1w': targetDate = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000); break // 1周
    case '1M': targetDate = new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000); break // 1月
    case '1y': targetDate = new Date(now.getTime() + 365 * 24 * 60 * 60 * 1000); break // 1年
    case 'permanent': 
      // 永久禁用设为当前时间加上100年
      targetDate = new Date(now);
      targetDate.setFullYear(targetDate.getFullYear() + 100);
      break;
    default: return null
  }
  
  // 转换为ISO 8601格式：yyyy-MM-dd'T'HH:mm:ss
  const year = targetDate.getFullYear();
  const month = String(targetDate.getMonth() + 1).padStart(2, '0');
  const day = String(targetDate.getDate()).padStart(2, '0');
  const hours = String(targetDate.getHours()).padStart(2, '0');
  const minutes = String(targetDate.getMinutes()).padStart(2, '0');
  const seconds = String(targetDate.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
}

// 提交冻结
const confirmFreeze = async () => {
  if (!freezeTargetUser.value) return

  const expireTime = calculateExpireTime(freezeForm.expireTimeOption)

  const params: WalletFreezeParams = {
    buyerUserId: freezeTargetUser.value.buyerUserId,
    actionType: 2, // 2-冻结
    amount: freezeForm.amount,
    expireTime: expireTime,
    reason: freezeForm.reason
  }

  try {
    const response = await UserService.freezeWallet(params)
    
    if (response.code === 200 || response.code === "200") {
      ElMessage.success('冻结成功')
      freezeDialogVisible.value = false
      loadUserList()
    } else {
      ElMessage.error(response.message || '冻结失败')
    }
  } catch (error: any) {
    ElMessage.error('网络错误：' + error.message)
  }
}





// 禁用用户发布动态
const handleTrendsDisable = (user: UserItem) => {
  trendsUser.value = user
  trendsAction.value = '禁用'
  trendsDialogVisible.value = true
}

// 启用用户发布动态
const handleTrendsEnable = (user: UserItem) => {
  trendsUser.value = user
  trendsAction.value = '启用'
  trendsDialogVisible.value = true
}

// 提交禁用/启用发布动态
const confirmTrendsAction = async () => {
  if (!trendsUser.value) return
  
  const params: BuyerTrendsParam = {
    buyerUserId: trendsUser.value.buyerUserId,
    state: trendsAction.value === '禁用' ? 0 : 1 // 0-禁用, 1-启用
  }

  try {
    const response = await UserService.updateUserTrends(params)
    
    if (response.code === "200") {
      ElMessage.success(`${trendsAction.value}成功`)
      trendsDialogVisible.value = false
      loadUserList()
    } else {
      ElMessage.error(response.message || `${trendsAction.value}失败`)
    }
  } catch (error: any) {
    ElMessage.error('提交失败：' + error.message)
  }
}

// 禁用用户IM
const handleImDisable = (user: UserItem) => {
  imUser.value = user
  imAction.value = '禁用'
  imDialogVisible.value = true
}

// 启用用户IM
const handleImEnable = (user: UserItem) => {
  imUser.value = user
  imAction.value = '启用'
  imDialogVisible.value = true
}

// 提交禁用/启用IM
const confirmImAction = async () => {
  if (!imUser.value) return
  
  const params: BuyerImParam = {
    buyerUserId: imUser.value.buyerUserId,
    status: imAction.value === '禁用' ? 0 : 1 // 0-禁用, 1-启用
  }

  try {
    const response = await UserService.updateUserIM(params)
    
    if (response.code === "200") {
      ElMessage.success(`${imAction.value}成功`)
      imDialogVisible.value = false
      loadUserList()
    } else {
      ElMessage.error(response.message || `${imAction.value}失败`)
    }
  } catch (error: any) {
    ElMessage.error('提交失败：' + error.message)
  }
}

// 初始化加载
onMounted(() => {
  loadUserList()
})
</script>

<style scoped>
/* 样式保持不变，可复用原有样式 */
.user-manage-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.manage-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.manage-card .el-card__header {
  background-color: #409eff;
  color: white;
  border-radius: 8px 8px 0 0;
  padding: 15px 20px;
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.user-list-section h3 {
  margin-bottom: 20px;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #409eff;
}

/* 操作按钮样式调整 */
    :deep(.operation-buttons) {
      display: flex;
      flex-wrap: wrap;
      gap: 6px;
      justify-content: center;
      align-items: center;
    }
    
    /* 操作列标题居中 */
    :deep(.el-table__header th.el-table__cell) {
      text-align: center;
    }

:deep(.operation-buttons .el-button--small) {
  padding: 4px 8px;
  min-width: 50px;
  font-size: 11px;
  height: 24px;
  line-height: 14px;
}

/* 针对不同文字长度的按钮做进一步调整 */
  :deep(.operation-buttons .el-button--small) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  
  .user-list-section h3 {
    padding-bottom: 10px;
  }

.pagination-wrapper {
  text-align: center;
  margin-top: 0;
  padding: 20px 0;
  background: white;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

/* 分页滚动容器样式 */
.pagination-scroll-wrapper {
  width: 100%;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
  margin-top: 20px;
  padding: 5px 0;
  box-sizing: border-box;
  /* 创建独立的滚动上下文 */
  contain: content;
}

/* 自定义滚动条样式 */
.pagination-scroll-wrapper::-webkit-scrollbar {
  height: 6px;
}

.pagination-scroll-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.pagination-scroll-wrapper::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.pagination-scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 移动端分页容器额外样式 */
@media screen and (max-width: 768px) {
  .pagination-scroll-wrapper {
    padding: 10px 0;
  }

  .pagination-wrapper {
    text-align: right;
    white-space: nowrap;
  }
}
</style>
